import userLogin from "@/api/login";
import { userInfo } from "@/api/user";
import { getToken,setToken,getUser,setUser } from "@/utils/loginInfo";

export const loginStore = {
    namespaced: true,
    state: {
        //  token
        token: getToken() || "",
        //  用户信息(用户名、用户id和ip)
        user: getUser() || {},
    },
    mutations: {
        setToken(state,value){
            state.token = value;
        },
        setUser(state,obj){
            state.user = obj;
        }
    },
    actions: {
        async login(context,data) {
            try{
                const {name, password} = data;
                //  result存储的是后端返回的数据
                const result = await userLogin({name,password});
                // console.log("@@@",result);
                if(result.code === 200){
                    context.commit("setToken",result.data.token);
                    context.commit("setUser",result.data.user);
                    setToken(result.data.token);
                    setUser(result.data.user);
                    return result.data.user.name;
                }else{
                    return Promise.reject(new Error(result.msg) || "登录失败")
                }
            }catch(error){
                // console.log("###",error);
                /*
                    error对象的结构
                    status: 响应状态码
                    response.data: 响应数据
                */
                return Promise.reject(new Error(error.response?.data?.msg) || "网络或服务器异常");
            }
        },

        async info(context, data){
            try{
                const result = await userInfo(data);
                if(result.code === 200){
                    return result.data;
                }
            }catch(error){
                return Promise.reject(new Error(error.response.data.msg));
            }
        }
    },
    getters: {
        
    }
}